package com.atguigu.tingshu.search.service.impl;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.FieldValue;
import co.elastic.clients.elasticsearch._types.SortOrder;
import co.elastic.clients.elasticsearch._types.aggregations.Aggregate;
import co.elastic.clients.elasticsearch._types.aggregations.Aggregation;
import co.elastic.clients.elasticsearch._types.aggregations.LongTermsBucket;
import co.elastic.clients.elasticsearch._types.query_dsl.BoolQuery;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.elasticsearch.core.search.Suggestion;
import co.elastic.clients.json.JsonData;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.tingshu.album.client.AlbumInfoFeignClient;
import com.atguigu.tingshu.album.client.CategoryFeignClient;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.util.PinYinUtils;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.album.BaseCategory1;
import com.atguigu.tingshu.model.album.BaseCategory3;
import com.atguigu.tingshu.model.album.BaseCategoryView;
import com.atguigu.tingshu.model.search.AlbumInfoIndex;
import com.atguigu.tingshu.model.search.AttributeValueIndex;
import com.atguigu.tingshu.model.search.SuggestIndex;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.query.search.AlbumIndexQuery;
import com.atguigu.tingshu.search.repository.AlbumIndexRepository;
import com.atguigu.tingshu.search.repository.SuggestIndexRepository;
import com.atguigu.tingshu.search.service.SearchService;
import com.atguigu.tingshu.user.client.UserInfoFeignClient;
import com.atguigu.tingshu.vo.album.AlbumStatVo;
import com.atguigu.tingshu.vo.search.AlbumInfoIndexVo;
import com.atguigu.tingshu.vo.search.AlbumSearchResponseVo;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;

import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.suggest.Completion;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;


@Slf4j
@Service
@SuppressWarnings({"all"})
public class SearchServiceImpl implements SearchService {
    @Resource
    private AlbumInfoFeignClient albumInfoFeignClient;
    @Resource
    private UserInfoFeignClient userInfoFeignClient;
    @Resource
    private CategoryFeignClient categoryFeignClient;

    @Resource
    private ElasticsearchClient elasticsearchClient;

    @Resource
    private AlbumIndexRepository albumIndexRepository;

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @Resource
    private SuggestIndexRepository suggestIndexRepository;
    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 获取排行榜数据
     * @param category1Id
     * @param dimension
     * @return
     */
    @Override
    public List<AlbumInfoIndexVo> findRankingList(Long category1Id, String dimension) {
        return (List<AlbumInfoIndexVo>) redisTemplate.opsForHash().get(RedisConstant.RANKING_KEY_PREFIX+category1Id,dimension);
    }

    /**
     * 更新排行榜
     */
    @Override
    public void updateLatelyAlbumRanking() {
        //获取一级分类IdList
        Result<List<BaseCategory1>> category1Res=categoryFeignClient.findAllCategory1();
        Assert.notNull(category1Res, "获取一级分类失败");
        List<BaseCategory1> category1List = category1Res.getData();
        Assert.notNull(category1List, "获取一级分类失败");

        for (BaseCategory1 baseCategory1 : category1List) {
            //  baseCategory1.getId()
            //  Hash数据结构： hset key field value;  key=category1Id field = 热度/播放量/订阅量/ value=热度data/播放量data;
            String[] rankingDimensionArray = new String[]{"hotScore", "playStatNum", "subscribeStatNum", "buyStatNum", "commentStatNum"};
            //  排行榜数据从哪里来的? es 中!
            for (String ranging : rankingDimensionArray) {
                //1、从es中获取List《AlbumInfoIndex》
                SearchResponse<AlbumInfoIndex> searchResponse=null;
                try {
                    searchResponse = elasticsearchClient.search(f -> f.index("albuminfo")
                            .query(q -> q.term(t -> t.field("category1Id").value(baseCategory1.getId())))
                            .sort(s -> s.field(d -> d.field(ranging).order(SortOrder.Desc)))
                            .size(10), AlbumInfoIndex.class);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                //  获取到当前执行结果集，将数据存储到缓存：
                List<AlbumInfoIndex> albumInfoIndexList = searchResponse.hits().hits().stream().map(Hit::source).collect(Collectors.toList());
                // 2、将数据存储到redis中,key=category1Id,field=ranging,value=List<albumInfoIndex>
                String rangKey = RedisConstant.RANKING_KEY_PREFIX+baseCategory1.getId();
                redisTemplate.opsForHash().put(rangKey,ranging,albumInfoIndexList);
            }

        }


    }

    /**
     * 根据关键词（专辑标题，简介，作者），自动补全
     * @param keyword
     * @return
     */
    @Override
    public List<String> completeSuggest(String keyword) {
        SearchResponse<SuggestIndex> searchResponse=null;
        //1.  根据用户输入的检索数据，从es中获取数据集合；并返回给用户;
        try {
            searchResponse = elasticsearchClient.search(s -> s.index("suggestinfo").
                            suggest(s1->s1.suggesters("keyword-suggest",s2->s2
                                    .prefix(keyword)
                                    .completion(cs->cs
                                            .field("keyword")
                                            .skipDuplicates(true)
                                            .fuzzy(sf->sf.fuzziness("auto"))
                                            .size(10)))
                                    .suggesters("keywordPinyin-suggest",s3->s3
                                            .prefix(keyword)
                                            .completion(cs->cs
                                                    .field("keywordPinyin")
                                                    .skipDuplicates(true)
                                                    .fuzzy(sf->sf.fuzziness("auto"))
                                                    .size(10)
                                            ))
                                    .suggesters("keywordSequence-suggest",s3->s3
                                            .prefix(keyword)
                                            .completion(cs->cs
                                                    .field("keywordSequence")
                                                    .skipDuplicates(true)
                                                    .fuzzy(sf->sf.fuzziness("auto"))
                                                    .size(10)
                                            ))
                            )
                    , SuggestIndex.class);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //  获取集合数据; 数据都在options;
        List<String> list = new ArrayList<>();
        list.addAll(getSuggestionTitle(searchResponse, "keyword-suggest"));
        list.addAll(getSuggestionTitle(searchResponse, "keywordPinyin-suggest"));
        list.addAll(getSuggestionTitle(searchResponse, "keywordSequence-suggest"));
        //  返回数据
        return list;
    }
    public Collection<String> getSuggestionTitle(SearchResponse<SuggestIndex> searchResponse, String suggest) {
        //  获取提词库中的数据:
        List<Suggestion<SuggestIndex>> suggestionList = searchResponse.suggest().get(suggest);
        //  判断集合不为空
        if(!CollectionUtils.isEmpty(suggestionList)){
            //  循环遍历集合
            for (Suggestion<SuggestIndex> suggestIndexSuggestion : suggestionList) {
                //  获取数据;
                List<String> list = suggestIndexSuggestion.completion().options().stream().map(option -> {
                    String title = option.source().getTitle();
                    return title;
                }).collect(Collectors.toList());
                //  返回集合数据；
                return list;
            };
        }
        //  默认返回
        return new ArrayList<>();
    }

    /**
     * 根据一级分类ID，获取频道页展示数据
     * @param category1Id
     * @return
     */
    @Override
    public List<Map<String, Object>> channel(Long category1Id) {


        //1、远程调用，专辑微服务->根据一级分类ID，获取频道页三级分类列表--Category3IdList
        Result<List<BaseCategory3>> topBaseCategory3Res = categoryFeignClient.findTopBaseCategory3(category1Id);
        //判断
        Assert.notNull(topBaseCategory3Res, "远程调用获取三级分类数据失败失败");
        //获取三级分类数据
        List<BaseCategory3> category3List = topBaseCategory3Res.getData();
        //判断
        Assert.notNull(category3List, "远程获取三级分类数据失败");
        //将category3List-》map （key=category3Id,value=BaseCategory3）
        Map<Long, BaseCategory3> baseCategory3Map = category3List.stream().collect(Collectors.toMap(BaseCategory3::getId, baseCategory3 -> baseCategory3));

        //获取三级分类ID集合
        List<Long> category3IdList = category3List.stream().map(BaseCategory3::getId).collect(Collectors.toList());


        //2、根据Category3IdList，每个三级分类的前六条置顶专辑
        //2.1、定义dsl
        //2.2、指定dsl、
        //   定义查询条件，将三级分类ID->valueList，category3IdList --> List<FieldValue>
        List<FieldValue> fieldValueList = category3IdList.stream().map(category3Id -> FieldValue.of(category3Id)).collect(Collectors.toList());
        SearchResponse<AlbumInfoIndex> searchResponse=null;
        try {
            //执行dsl，并获取结果
            //获取三级分类，对应下的按照热度置顶，前6个专辑，按照热度 desc
            searchResponse = elasticsearchClient.search(s -> s.index("albuminfo")
                            .query(q -> q.bool(b -> b.filter(f -> f.terms(t -> t.field("category3Id").terms(t1 -> t1.value(fieldValueList))))))
                            .aggregations("agg_category3Id", a -> a.terms(t -> t.field("category3Id"))
                                    .aggregations("agg_topSix", a1 -> a1.topHits(t1 -> t1.size(6).sort(st -> st.field(f -> f.field("hotScore").order(SortOrder.Desc)))))
                            )
                    ,
                    AlbumInfoIndex.class);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //2.3、结果类型转换，从聚合中获取数据
        Aggregate aggregate = searchResponse.aggregations().get("agg_category3Id");
        List<Map<String, Object>> collect = searchResponse.aggregations().get("agg_category3Id").lterms().buckets().array().stream().map(
                bucket -> {
                    HashMap<String, Object> map = new HashMap<>();
                    //获取三级分类ID，
                    long category3Id = bucket.key();
                    //获取三级分类，对应下的按照热度置顶，前6个专辑，按照热度 desc
                    List<AlbumInfoIndex> albumInfoIndexList = bucket.aggregations().get("agg_topSix").topHits().hits().hits().stream().map(
                            hit -> {
                                String source = hit.source().toString();
                                AlbumInfoIndex albumInfoIndex = JSONObject.parseObject(source, AlbumInfoIndex.class);
                                return albumInfoIndex;
                            }
                    ).collect(Collectors.toList());
                    //根据三级分类ID，获取三级分类对象
                    map.put("baseCategory3", baseCategory3Map.get(category3Id));
                    //设置三级分类下的专辑列表
                    map.put("list", albumInfoIndexList);
                    return map;
                }
        ).collect(Collectors.toList());

        //3、返回结果
        return collect;
    }

    /**
     * 全文检索专辑
     * @param albumIndexQuery
     * @return
     */
    @Override
    public AlbumSearchResponseVo search(AlbumIndexQuery albumIndexQuery) {
        //1 定义DSl
        //1、根据专辑标题，专辑介绍，作者，查，多条件模糊查询

        SearchRequest searchRequest = this.queryBuildDsl(albumIndexQuery);

        SearchResponse<AlbumInfoIndex> searchResponse;
        try {
            //2 执行DSL
            searchResponse = elasticsearchClient.search(searchRequest, AlbumInfoIndex.class);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        //3 类型转换
        AlbumSearchResponseVo searchResponseVo = this.parseResultData(searchResponse);
        searchResponseVo.setTotal(searchResponse.hits().total().value());
        searchResponseVo.setPageNo(albumIndexQuery.getPageNo());
        searchResponseVo.setPageSize(albumIndexQuery.getPageSize());
        //  设置总页数; 10 3 4; 9 3 3
        //        searchResponseVo.setTotalPages(searchResponseVo.getTotal() % albumIndexQuery.getPageSize() == 0 ?
        //                searchResponseVo.getTotal() / albumIndexQuery.getPageSize() :
        //                searchResponseVo.getTotal() / albumIndexQuery.getPageSize() + 1);
        Long totalPages = (searchResponseVo.getTotal() + searchResponseVo.getPageSize() - 1) / searchResponseVo.getPageSize();
        searchResponseVo.setTotalPages(totalPages);
        //返回结果
        return searchResponseVo;
    }
    /**
     * 解析结果数据
     *
     * @param searchResponse
     * @return
     */
    public AlbumSearchResponseVo parseResultData(SearchResponse<AlbumInfoIndex> searchResponse) {
        /*
            private List<AlbumInfoIndexVo> list = new ArrayList<>();
            private Long total;//总记录数
            private Integer pageSize;//每页显示的内容
            private Integer pageNo;//当前页面
            private Long totalPages;
         */
        //  创建对象
        AlbumSearchResponseVo albumSearchResponseVo = new AlbumSearchResponseVo();
        //  存储的是专辑列表集合; List<AlbumInfoIndexVo> list hits().hits().source
        List<AlbumInfoIndexVo> albumInfoIndexVoList = searchResponse.hits().hits().stream().map(hit -> {
            //  创建对象
            AlbumInfoIndexVo albumInfoIndexVo = new AlbumInfoIndexVo();
            //  赋值:
            AlbumInfoIndex albumInfoIndex = hit.source();
            BeanUtils.copyProperties(albumInfoIndex, albumInfoIndexVo);
            //  判断当前专辑标题是否有高亮;
            if (null != hit.highlight().get("albumTitle")) {
                //  获取高亮的标题;
                String albumTitle = hit.highlight().get("albumTitle").get(0);
                albumInfoIndexVo.setAlbumTitle(albumTitle);
            }
            //  返回数据
            return albumInfoIndexVo;
        }).collect(Collectors.toList());
        albumSearchResponseVo.setList(albumInfoIndexVoList);
        //  返回对象
        return albumSearchResponseVo;
    }
    /**
     * 构建dsl语句
     *
     * @param albumIndexQuery
     * @return
     */
    public SearchRequest queryBuildDsl(AlbumIndexQuery albumIndexQuery) {
        //  通过Builder() 创建对象：
        SearchRequest.Builder searchRequestBuilder = new SearchRequest.Builder();
        searchRequestBuilder.index("albuminfo");
        //  query->bool
        BoolQuery.Builder boolQuerybuilder = new BoolQuery.Builder();
        //  检索的入口：根据关键词：
        if (!StringUtils.isEmpty(albumIndexQuery.getKeyword())) {
            boolQuerybuilder.should(s -> s.match(m -> m.field("albumTitle").query(albumIndexQuery.getKeyword())))
                    .should(s -> s.match(m -> m.field("albumIntro").query(albumIndexQuery.getKeyword())))
                    .should(s -> s.match(m -> m.field("announcerName").query(albumIndexQuery.getKeyword())));
            //  设置高亮
            searchRequestBuilder.highlight(h -> h.fields("albumTitle", f -> f.preTags("<span style=color:red>").postTags("</span>")));
        }
        //  检索的第二个入口：分类：一级分类，二级分类，三级分类;
        if (!StringUtils.isEmpty(albumIndexQuery.getCategory1Id())) {
            boolQuerybuilder.filter(f -> f.term(t -> t.field("category1Id").value(albumIndexQuery.getCategory1Id())));
        }
        if (!StringUtils.isEmpty(albumIndexQuery.getCategory2Id())) {
            boolQuerybuilder.filter(f -> f.term(t -> t.field("category2Id").value(albumIndexQuery.getCategory2Id())));
        }
        if (!StringUtils.isEmpty(albumIndexQuery.getCategory3Id())) {
            boolQuerybuilder.filter(f -> f.term(t -> t.field("category3Id").value(albumIndexQuery.getCategory3Id())));
        }
        //  根据属性与属性值进行过滤;
        List<String> attributeList = albumIndexQuery.getAttributeList();
        //  判断集合是否为空
        if (!CollectionUtils.isEmpty(attributeList)) {
            //  循环遍历： 属性id:属性值id
            for (String attr : attributeList) {
                //  将attr 进行分割：
                String[] split = attr.split(":");
                //  判断
                if (null != split && split.length == 2) {
                    boolQuerybuilder.filter(f -> f.nested(n -> n.path("attributeValueIndexList")
                            .query(q -> q.bool(b -> b.must(m -> m.match(m1 -> m1.field("attributeValueIndexList.attributeId").query(split[0])))
                                    .must(m -> m.match(m1 -> m1.field("attributeValueIndexList.valueId").query(split[1])))
                            ))
                    ));
                }
            }
        }
        //  排序：排序（综合排序[1:desc] 播放量[2:desc] 发布时间[3:desc]；asc:升序 desc:降序）
        String order = albumIndexQuery.getOrder();
        if (!StringUtils.isEmpty(order)) {
            //  分割：
            String[] split = order.split(":");
            if (null != split && split.length == 2) {
                String field = "";
                //  判断：
                switch (split[0]) {
                    case "1":
                        field = "hotScore";
                        break;
                    case "2":
                        field = "playStatNum";
                        break;
                    case "3":
                        field = "createTime";
                        break;
                }
                //  设置排序字段：与排序规则；
                String finalField = field;
                searchRequestBuilder.sort(s -> s.field(f -> f.field(finalField).order("asc".equals(split[1]) ? SortOrder.Asc : SortOrder.Desc)));
            }
        }
        //  分页：
        int from = (albumIndexQuery.getPageNo() - 1) * albumIndexQuery.getPageSize();
        searchRequestBuilder.from(from);
        searchRequestBuilder.size(albumIndexQuery.getPageSize());
        BoolQuery boolQuery = boolQuerybuilder.build();
        //        Query.Builder builder = new Query.Builder();
        //        Query query = builder.build();
        //  query{};
        searchRequestBuilder.query(boolQuery._toQuery());
        SearchRequest searchRequest = searchRequestBuilder.build();
        System.out.println("dsl:\t" + searchRequest.toString());
        //  返回对象；
        return searchRequest;
    }

    /**
     * 专辑上架
     * @param albumId
     */
    @Override
    public void upperAlbum(Long albumId) {
        AlbumInfoIndex albumInfoIndex = new AlbumInfoIndex();

        CompletableFuture<AlbumInfo> albumCompletableFuture = CompletableFuture.supplyAsync(() -> {
            //1. 获取专辑信息
            //向service-album，发起远程调用，
            Result<AlbumInfo> albumInfoRes = albumInfoFeignClient.getAlbumInfo(albumId);
            Assert.notNull(albumInfoRes, "远程调用获取专辑信息失败");
            AlbumInfo albumInfo = albumInfoRes.getData();
            Assert.notNull(albumInfo, "远程获取albumInfo失败");
            //属性copy
            BeanUtils.copyProperties(albumInfo, albumInfoIndex);


            //2. 获取专辑属性属性值列表
            //albumInfo中就有，StreamAPI，将List<AlbumAttributeValue> --> List<AttributeValueIndex>
            List<AttributeValueIndex> attributeValueIndexList = albumInfo.getAlbumAttributeValueVoList().stream().map(albumAttributeValue -> {
                AttributeValueIndex attributeValueIndex = new AttributeValueIndex();
                attributeValueIndex.setAttributeId(albumAttributeValue.getAttributeId());
                attributeValueIndex.setValueId(albumAttributeValue.getValueId());
                return attributeValueIndex;
            }).collect(Collectors.toList());
            //设置属性属性值列表
            albumInfoIndex.setAttributeValueIndexList(attributeValueIndexList);

            return albumInfo;
        },threadPoolExecutor).exceptionallyAsync((ex)->{
            System.out.println(ex.getMessage());
            return new AlbumInfo();
        });

        CompletableFuture<Void> userCompletableFuture = albumCompletableFuture.thenAcceptAsync(albumInfo -> {
            //3. 获取专辑的作者昵称
            //向service-user服务发起远程调用，by albumInfo.getUserId, 获取用户信息
            //由于非垂直，允许用户和管理员上下架，因此，传参userId，不再threadLocal
            Result<UserInfoVo> userInfoRes = userInfoFeignClient.getUserInfo(albumInfo.getUserId());
            Assert.notNull(userInfoRes, "远程调用获取用户信息失败");
            UserInfoVo userInfo = (UserInfoVo) userInfoRes.getData();
            Assert.notNull(userInfo, "远程获取userInfo失败");
            //设置作者昵称
            albumInfoIndex.setAnnouncerName(userInfo.getNickname());
        }, threadPoolExecutor).exceptionally(ex->{
            System.out.println(ex.getMessage());
            return null;
        });

        CompletableFuture<Void> categoryCompletableFuture = albumCompletableFuture.thenAcceptAsync(albumInfo -> {
            //4. 获取分类信息，
            //向service-album, 发起远程调用，根据AlbbumInfo.category3Id，查询分类信息
            Result<BaseCategoryView> categoryViewRes = categoryFeignClient.getCategoryView(albumInfo.getCategory3Id());
            Assert.notNull(categoryViewRes, "远程调用获取分类信息失败");
            BaseCategoryView categoryView = categoryViewRes.getData();
            Assert.notNull(categoryView, "远程获取baseCategoryView失败");
            //设置category2Id，category2Id
            albumInfoIndex.setCategory1Id(categoryView.getCategory1Id());
            albumInfoIndex.setCategory2Id(categoryView.getCategory2Id());

        }, threadPoolExecutor).exceptionally(ex->{
                System.out.println(ex.getMessage());
                return null;
        });

        CompletableFuture<Void> statCompletableFuture = CompletableFuture.runAsync(() -> {

            // 5. 获取专辑stat信息
            //统计数据：播放量，订阅量，购买量，评论量，评分，热门度; album_stat 留作业！
            //向service-album，发起远程调用，根据albumId，获取专辑统计信息
            Result<AlbumStatVo> albumStatRes = albumInfoFeignClient.getAlbumStat(albumId);
            Assert.notNull(albumStatRes, "远程调用获取专辑统计信息失败");
            AlbumStatVo albumStatVo = albumStatRes.getData();
            Assert.notNull(albumStatVo, "远程获取albumStatVo失败");
            //属性copy
            BeanUtils.copyProperties(albumStatVo,albumInfoIndex);
            albumInfoIndex.setHotScore((double) new Random().nextInt(1000000));
        }, threadPoolExecutor).exceptionally(ex -> {
            System.out.println(ex.getMessage());
            return null;
        });

        //  通常：get方法只调用一次! 应该将方法放在最后;
        try {
            System.out.println("category:"+categoryCompletableFuture.get());
            System.out.println("user:"+userCompletableFuture.get());
            if (ObjectUtils.isEmpty(albumCompletableFuture.get())){
                log.info("远程调用失败");
                return;
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }

        CompletableFuture.allOf(
                albumCompletableFuture,
                userCompletableFuture,
                categoryCompletableFuture,
                statCompletableFuture
        ).join();
        //6. 整合到自定义VO，AlbumInfoIndex，中
        //7. 保存到ES中

        //  将这个 albumInfoIndex 插入到es中
        log.info("将数据插入到es中");
        albumIndexRepository.save(albumInfoIndex);
        //8. **优化：**
        //   1. 异步编排+线程池优化，
        //   2. 远程调用异常，统一处理

        // 9. 保存提词库!
        SuggestIndex suggestIndex = new SuggestIndex();
        suggestIndex.setId(UUID.randomUUID().toString().replace("-",""));
        suggestIndex.setTitle(albumInfoIndex.getAlbumTitle());
        suggestIndex.setKeyword(new Completion(new String[]{albumInfoIndex.getAlbumTitle()}));
        suggestIndex.setKeywordPinyin(new Completion(new String[] {PinYinUtils.toHanyuPinyin(albumInfoIndex.getAlbumTitle())}));
        suggestIndex.setKeywordSequence(new Completion(new String[] {PinYinUtils.getFirstLetter(albumInfoIndex.getAlbumTitle())}));

        this.suggestIndexRepository.save(suggestIndex);

        //  专辑简介提词
        SuggestIndex albumIntroSuggestIndex = new SuggestIndex();
        albumIntroSuggestIndex.setId(UUID.randomUUID().toString().replaceAll("-",""));
        albumIntroSuggestIndex.setTitle(albumInfoIndex.getAlbumIntro());
        albumIntroSuggestIndex.setKeyword(new Completion(new String[]{albumInfoIndex.getAlbumIntro()}));
        albumIntroSuggestIndex.setKeywordPinyin(new Completion(new String[]{PinYinUtils.toHanyuPinyin(albumInfoIndex.getAlbumIntro())}));
        albumIntroSuggestIndex.setKeywordSequence(new Completion(new String[]{PinYinUtils.getFirstLetter(albumInfoIndex.getAlbumIntro())}));
        this.suggestIndexRepository.save(albumIntroSuggestIndex);

        // 专辑主播提词
        SuggestIndex announcerSuggestIndex = new SuggestIndex();
        announcerSuggestIndex.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        announcerSuggestIndex.setTitle(albumInfoIndex.getAnnouncerName());
        announcerSuggestIndex.setKeyword(new Completion(new String[]{albumInfoIndex.getAnnouncerName()}));
        announcerSuggestIndex.setKeywordPinyin(new Completion(new String[]{PinYinUtils.toHanyuPinyin(albumInfoIndex.getAnnouncerName())}));
        announcerSuggestIndex.setKeywordSequence(new Completion(new String[]{PinYinUtils.getFirstLetter(albumInfoIndex.getAnnouncerName())}));
        suggestIndexRepository.save(announcerSuggestIndex);

    }

    @Override
    public void lowerAlbum(Long albumId) {
        //  删除
        albumIndexRepository.deleteById(albumId);
    }


}
